package com.zyh.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyh.article.domain.Articles;
import com.zyh.article.mapper.ArticlesMapper;
import com.zyh.article.service.IArticlesService;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.core.domain.R;
import com.zyh.common.core.domain.entity.SysUser;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.system.service.ISysUserService;
import com.zyh.websocket.constant.MessageConstant;
import com.zyh.websocket.entity.Message;
import com.zyh.websocket.mapper.MessageMapper;
import com.zyh.websocket.service.MessageBaseService;
import com.zyh.websocket.service.MessageSenderService;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 文章管理Service业务层处理
 *
 * @author zhangyangheng
 * @date 2025-03-15
 */
@Service
public class ArticlesServiceImpl extends ServiceImpl<ArticlesMapper, Articles>
        implements IArticlesService {
    public static final Logger logger = LoggerFactory.getLogger(ArticlesServiceImpl.class);


    @Autowired
    private ArticlesMapper articlesMapper;

    @Autowired
    private MessageSenderService messageSendService;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageBaseService messageBaseService;

    /**
     * 查询文章管理
     *
     * @param articleId 文章管理主键
     * @return 文章管理
     */
    @Override
    public Articles selectArticlesByArticleId(Long articleId) {
        return articlesMapper.selectArticlesByArticleId(articleId);
    }

    /**
     * 查询文章管理列表
     *
     * @param articles 文章管理
     * @return 文章管理
     */
    @Override
    public List<Articles> selectArticlesList(Articles articles) {
        articles.setCreateBy(SecurityUtils.getUsername());
        return articlesMapper.selectArticlesList(articles);
    }

    /**
     * 新增文章管理
     *
     * @param articles 文章管理
     * @return 结果
     */
    @Override
    public int insertArticles(Articles articles) {
        return articlesMapper.insertArticles(articles);
    }

    /**
     * 修改文章管理
     *
     * @param articles 文章管理
     * @return 结果
     */
    @Override
    public int updateArticles(Articles articles) {
        return articlesMapper.updateArticles(articles);
    }

    /**
     * 批量删除文章管理
     *
     * @param articleIds 需要删除的文章管理主键
     * @return 结果
     */
    @Override
    public int deleteArticlesByArticleIds(Long[] articleIds) {
        return articlesMapper.deleteArticlesByArticleIds(articleIds);
    }

    /**
     * 删除文章管理信息
     *
     * @param articleId 文章管理主键
     * @return 结果
     */
    @Override
    public int deleteArticlesByArticleId(Long articleId) {
        return articlesMapper.deleteArticlesByArticleId(articleId);
    }

    /**
     * 作者发布文章
     *
     * @param articles
     * @return
     */
    @Override
    public int changePublishStatus(Articles articles) {
        Long articleId = articles.getArticleId();
        Articles selectOne = articlesMapper.selectOne(new LambdaQueryWrapper<Articles>()
                .eq(Articles::getArticleId, articleId)
                .eq(Articles::getDelFlag, "0"));
        // 判断文章是否存在
        if (Objects.isNull(selectOne)) {
            return 0;
        }

        String currentUserName = SecurityUtils.getUsername(); // 提取用户名
        Date currentDate = new Date(); // 提取当前时间

        if ("4".equals(selectOne.getStatus())) {
            // 允许被拒文章重新提交发布申请
            if ("1".equals(articles.getIsPublish())) {
                return articlesMapper.update(null, new LambdaUpdateWrapper<Articles>()
                        .eq(Articles::getArticleId, articleId)
                        .set(Articles::getStatus, "1") // 重置为待审核
                        .set(Articles::getIsPublish, "1")
                        .set(Articles::getRejectReason, null)
                        .set(Articles::getPublishBy, currentUserName)
                        .set(Articles::getPublishTime, currentDate)
                        .set(Articles::getUpdateBy, currentUserName)
                        .set(Articles::getUpdateTime, currentDate));
            }
            return 0; // 非发布操作保持原状态
        }
        String isPublish = articles.getIsPublish();
        if (StringUtil.isNullOrEmpty(isPublish)) {
            return 0;
        }

        LambdaUpdateWrapper<Articles> updateWrapper = new LambdaUpdateWrapper<Articles>()
                .eq(Articles::getArticleId, articleId)
                .set(Articles::getIsPublish, isPublish)
                .set(Articles::getUpdateBy, currentUserName)
                .set(Articles::getUpdateTime, currentDate);

        if ("0".equals(isPublish)) {
            updateWrapper
                    .set(Articles::getStatus, "0")
                    .set(Articles::getPublishBy, null)
                    .set(Articles::getPublishTime, null);
        } else {
            updateWrapper
                    .set(Articles::getStatus, "1")
                    .set(Articles::getPublishBy, currentUserName)
                    .set(Articles::getPublishTime, currentDate);
        }
        int update = articlesMapper.update(selectOne, updateWrapper);
        // 发布文章才发送审核请求，下架不发送。
        if ("1".equals(articles.getIsPublish())) {
            SysUser sendUser = userService.selectUserByUserName(currentUserName);
            List<SysUser> adminList = userService.selectUsersByRoleKey("commonAdmin");
            adminList.forEach(admin -> {
                // 构建消息
                Message message = new Message();
                message.setReceiverId(admin.getUserId());
                message.setType(MessageConstant.APPROVAL_MSG);
                message.setSubType(MessageConstant.SubType.APPROVAL_REQUEST);
                message.setContent("您有一条待审核的文章！ 《" + selectOne.getTitle()+"》");
                message = messageBaseService.buildMessage(message, sendUser.getUserId());
                try {
                    // 给所有管理员发消息
                    messageSendService.sendApprovalRequest(admin.getUserId().toString(), message);
                    // 消息入库
                    messageMapper.insert(message);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        return update;
    }

    /**
     * 审核员修改文章状态
     *
     * @param articles
     * @return
     */
    @Override
    public AjaxResult changeArticleStatus(Articles articles) {
        if (Objects.isNull(articles) || Objects.isNull(articles.getArticleId())
                || Objects.isNull(articles.getStatus())) {
            return AjaxResult.error();
        }

        Articles dbArticle = articlesMapper.selectOne(new LambdaQueryWrapper<Articles>()
                .eq(Articles::getArticleId, articles.getArticleId()));
        if (Objects.isNull(dbArticle)) {
            return AjaxResult.error("错误！文章不存在");
        }
        if (!"1".equals(dbArticle.getStatus())) {
            return AjaxResult.error("用户已取消发布！");
        }
        LambdaUpdateWrapper<Articles> wrapper = new LambdaUpdateWrapper<Articles>()
                .eq(Articles::getArticleId, articles.getArticleId())
                .eq(Articles::getIsPublish, "1")
                .eq(Articles::getDelFlag, "0")
                .set(Articles::getReviewerBy, SecurityUtils.getUsername())
                .set(Articles::getReviewedTime, new Date())
                .set(Articles::getUpdateBy, SecurityUtils.getUsername())
                .set(Articles::getUpdateTime, new Date());

        if ("4".equals(articles.getStatus())) {
            // 拒绝逻辑
            wrapper.set(Articles::getStatus, "4")
                    .set(Articles::getRejectReason, articles.getRejectReason())
                    .set(Articles::getIsPublish, "0")
                    .set(Articles::getPublishBy, (String) null)
                    .set(Articles::getPublishTime, (Date) null);
        } else if ("2".equals(articles.getStatus())) {
            // 通过逻辑（仅修改状态）
            wrapper.set(Articles::getStatus, "2");
        }
        int update = articlesMapper.update(null, wrapper);
        // 发送消息给提交申请的用户
        if (update > 0) {
            String result = "4".equals(articles.getStatus()) ? "拒绝通过" : "已通过";
            StringBuilder sb = new StringBuilder();
            sb.append("您的标题为《" + dbArticle.getTitle() + "》文章的审核结果是：").append(result);
            if ("4".equals(articles.getStatus()) && !StringUtil.isNullOrEmpty(articles.getRejectReason())) {
                sb.append(",原因是：").append(articles.getRejectReason());
            }
            SysUser receiverUser = userService.selectUserByUserName(dbArticle.getCreateBy());
            Message message = new Message();
            message.setReceiverId(receiverUser.getUserId());
            message.setType(MessageConstant.APPROVAL_MSG);
            message.setSubType(MessageConstant.SubType.APPROVAL_RESULT);
            message.setContent(sb.toString());
            message = messageBaseService.buildMessage(message, SecurityUtils.getUserId());
            messageSendService.sendApprovalResult(message);
        }
        return update > 0 ? AjaxResult.success("审核成功！") : AjaxResult.error("审核失败！");
    }

    @Override
    public int like(Long articleId) {
        return 0;
    }

    @Override
    public List<Articles> selectArticlesListAll(Articles articles) {
        articles.setCreateBy(SecurityUtils.getUsername());
        return articlesMapper.selectArticlesListAll(articles);
    }
}